<?php
require_once(SITE_ROOT . 'class/db/DB.class.php');
require_once(SITE_ROOT . 'class/bean/Division.class.php');

class DBDivision {
	
	public function getDivisions() {
		$db = new DB();
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('SELECT DISTINCT `division#`, `size` FROM `tdivision`')) {
			$stmt->execute();
			$stmt->bind_result($divisionID, $size);
			
			$divisions = new ArrayObject();
			
			while ($stmt->fetch()) {
				$division = new Division();
				$division->setDivisionID($divisionID);
				$division->setSize($size);
				$divisions->append($division);
			}			
			$stmt->close();
			$db->disconnect();
			
			return $divisions;
		}
	}
	
	public function getDivisionsByCountry($country) {
		$db = new DB();
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('SELECT `division#`, `size` FROM `tdivision` WHERE `country#` = ?')) {
			$stmt->bind_param('i', $countryID);
			$countryID = $country->getCountryID();
			$stmt->execute();
			$stmt->bind_result($divisionID, $size);
			
			$divisions = new ArrayObject();
			
			while ($stmt->fetch()) {
				$division = new Division();
				$division->setDivisionID($divisionID);
				$division->setSize($size);
				$division->setCountry($country);
				$divisions->append($division);
			}			
			$stmt->close();
			$db->disconnect();
			
			return $divisions;
		}
	}
	
	public function saveDivisions($divisions) {
		$db = new DB;
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('INSERT INTO `tdivision` (`country#`, `division#`, `size`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE `size`=VALUES(`size`)')) {
			foreach ($divisions as $division) {
				$stmt->bind_param('iii', $countryID, $divisionID, $size);
				
				$countryID = $division->getCountry()->getCountryID();
				$divisionID = $division->getDivisionID();
				$size = $division->getSize();
				
				$stmt->execute();
			}
			$stmt->close();
			$db->disconnect();
		}
	}
	
	public function deleteDivisionsByCountry($country) {
		$db = new DB();
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('DELETE FROM `tdivision` WHERE `country#` = ?')) {
			$stmt->bind_param('i', $countryID);
			$countryID = $country->getCountryID();
			$stmt->execute();			
			$stmt->close();
			$db->disconnect();
		}
	}
	
}

?>